
package com.ifcar.app.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.widget.Toast;

import com.ifcar.app.activity.ShareToMicroBlog;
import com.ifcar.app.model.Comment;
import com.ifcar.app.activity.R;

public class ShareUtil {
    public static void showShareDialog(final Context context, final String title,
            final Map<String, Object> map, String bi, String docTitle) {
        if (map == null) {
            return;
        }
        
        if (TextUtils.isEmpty(bi)) {
            return;
        }
        
        final String pi = (String) ModelUtils.getValue(map, Comment.PARAM_PI);
        String tmpDocid = null;
        if (!TextUtils.isEmpty(pi)) {
            String[] ss = pi.split("_");
            if (ss != null && ss.length > 0) {
                tmpDocid = ss[0];
            }
        }
        final String docid = tmpDocid;
        if (TextUtils.isEmpty(docid)) {
            return;
        }
        
        final String p = (String) ModelUtils.getValue(map, Comment.PARAM_P);        
        if (TextUtils.isEmpty(p)) {
            return;
        }
        
        showShareDialog(context, title, bi, docid, p, docTitle);
        
    }
    
    public static void showShareDialog(final Context context, final String title,
            final Map<String, Object> map) {
        if (map == null) {
            return;
        }
        
        final String bi = (String) ModelUtils.getValue(map, Comment.PARAM_BI);
        if (TextUtils.isEmpty(bi)) {
            return;
        }
        
        final String pi = (String) ModelUtils.getValue(map, Comment.PARAM_PI);
        String tmpDocid = null;
        if (!TextUtils.isEmpty(pi)) {
            String[] ss = pi.split("_");
            if (ss != null && ss.length > 0) {
                tmpDocid = ss[0];
            }
        }
        final String docid = tmpDocid;
        if (TextUtils.isEmpty(docid)) {
            return;
        }
        
        final String p = (String) ModelUtils.getValue(map, Comment.PARAM_P);        
        if (TextUtils.isEmpty(p)) {
            return;
        }
        
        final String docTitle = (String)ModelUtils.getValue(map, Comment.PARAM_S);
        
        showShareDialog(context, title, bi, docid, p, docTitle);
        
    }
    
    
    /**
     * 单条跟帖分享
     * @param context
     * @param title 对话框名称
     * @param bi 版面id
     * @param docid 文章id
     * @param p 最后楼层p
     * @param docTitle 文章id
     */
    public static void showShareDialog(final Context context, final String title, final String bi, final String docid, final String p, final String shareTitle) {

        if (TextUtils.isEmpty(bi)) {
            return;
        }

        if (TextUtils.isEmpty(docid)) {
            return;
        }
           
        if (TextUtils.isEmpty(p)) {
            return;
        }
        
        new AlertDialog.Builder(context).setTitle("分享").setItems(
                new String[] {
                        context.getResources().getString(R.string.share_to_weibo),
                        context.getResources().getString(R.string.share_to_sina),
                        context.getResources().getString(R.string.share_to_qq),
                        context.getResources().getString(R.string.share_to_renren),
                        context.getResources().getString(R.string.share_to_ydnote),
                        context.getResources().getString(R.string.share_to_sms),
                        context.getResources().getString(R.string.share_to_email),
                        context.getResources().getString(R.string.share_to_other),
                }, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // TODO Auto-generated method stub
                        Intent shareintent = new Intent(context, ShareToMicroBlog.class);
                        shareintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        Bundle bundle = new Bundle();

                        bundle.putString("sharetitle", shareTitle);

                        bundle.putString("shareurl", StringUtil.TIEURL
                                + bi + "/" + docid + "/"
                                + p + ".html");
                        bundle.putString("board", "" + bi);
                        bundle.putString("postid", docid);
                         bundle.putString("pnum",p);
                        bundle.putBoolean("sharefloor", true);

                        switch (arg1) {
                            // 网易微博
                            case Constant.SHARE_NETEASE:
                                bundle.putInt("sharetype", 0);
                                shareintent.putExtras(bundle);
                                context.startActivity(shareintent);

                                break;
                            // 新浪微博
                            case Constant.SHARE_SINA:
                                bundle.putInt("sharetype", 1);
                                shareintent.putExtras(bundle);
                                context.startActivity(shareintent);

                                break;
                            // 腾讯微博
                            case Constant.SHARE_QQ:
                                bundle.putInt("sharetype", 2);
                                shareintent.putExtras(bundle);
                                context.startActivity(shareintent);
                                break;
                            case Constant.SHARE_RENREN:
                                bundle.putInt("sharetype", 3);
                                shareintent.putExtras(bundle);
                                context.startActivity(shareintent);
                                break;
                            // 有道笔记
                            case Constant.SHARE_YDNOTE:
                                 bundle.putInt("sharetype", 4);
                                 
                                 String tieurl = StringUtil.TIEURL+bi+"/"+docid+".html";
                                 String surl = HttpUtils.getDocShortUrl("wap",tieurl,context);
                                 bundle.putString("sharetitle", getCommentHtmlString(shareTitle, surl, 4));
                                 bundle.putString("sharetitleyd", shareTitle);

                                 shareintent.putExtras(bundle);
                                 context.startActivity(shareintent);
                                break;
                            case Constant.SHARE_SMS:
                                tieurl = StringUtil.TIEURL + bi + "/" + docid + ".html";
                                
                                new AsyncTask<String, Integer, Map>(){
                                    protected Map doInBackground(String... params) {
                                        // TODO Auto-generated method stub
                                        String shorturl = HttpUtils.getDocShortUrl("wap",params[0],context);
                                        String wwwshorturl = HttpUtils.getDocShortUrl("www",params[0],context);
                                        
                                        Map map = new HashMap();
                                        map.put("wap", shorturl);
                                        map.put("www", wwwshorturl);
                                        return map;
                                    }
                                    
                                    @Override
                                    protected void onPostExecute(Map result) {
                                        super.onPostExecute(result);
                                        String shorturl = (String)result.get("wap");
                                        String wwwshorturl   = (String)result.get("www");
                                        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
                                        sendIntent.putExtra("sms_body", context.getResources().getString(
                                                R.string.share_sms_tietext)
                                                + "《"
                                                + shareTitle
                                                + "》"
                                                + context.getResources().getString(R.string.share_with_u)
                                                + ":"
                                                + context.getResources().getString(R.string.share_url_wap)
                                                + " "
                                                + shorturl
                                                + " "
                                                + context.getResources().getString(R.string.share_url_www)
                                                + " " + wwwshorturl);
                                        sendIntent.setType("vnd.android-dir/mms-sms");
                                        context.startActivity(sendIntent);
 
                                    }
                                }.execute(tieurl);
                                
                               
                                
                                break;
                            case Constant.SHARE_EMAIL:
                                final List<ResolveInfo> sharelist = Tools.getShareTargets(context,"message/rfc822");
                                if (null != sharelist && sharelist.size() > 0) {
                                    try {
                                        tieurl = StringUtil.TIEURL + bi + "/" + docid + ".html";
                                       
                                       
                                        
                                        new AsyncTask<String, Integer, String>(){

                                            @Override
                                            protected String doInBackground(String... params) {
                                                // TODO Auto-generated method stub
                                                return HttpUtils.getDocShortUrl("www",params[0],context);
                                      
                                            }
                                            @Override
                                            protected void onPostExecute(String result) {
                                                super.onPostExecute(result);
                                                
                                                Intent emailIntent = new Intent(
                                                        android.content.Intent.ACTION_SEND);
                                                emailIntent.setType("message/rfc822");
                                                emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                                                        context.getResources().getString(
                                                                R.string.share_email_tietitle));

                                                String html = getCommentHtmlString(shareTitle, result, -1);

                                                emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
                                                        Html.fromHtml(html));
                                                context.startActivity(Intent.createChooser(emailIntent,
                                                        context.getResources().getString(
                                                                R.string.select_email_client)));
                                            }
                                            
                                        }.execute(tieurl);

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        Toast.makeText(
                                                context,
                                                context.getResources().getString(
                                                        R.string.share_email_failure),
                                                Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    Toast.makeText(
                                            context,
                                            context.getResources().getString(
                                                    R.string.share_email_noclient),
                                            Toast.LENGTH_SHORT).show();
                                }

                                break;
                            case Constant.SHARE_OTHER:
                                String tieurl2 = StringUtil.TIEURL
                                        + bi + "/" + docid
                                        + ".html";
                                
                                new AsyncTask<String, Integer, Map>(){
                                    @Override
                                    protected Map doInBackground(String... params) {
                                        // TODO Auto-generated method stub
                                        String shorturl = HttpUtils.getDocShortUrl("wap",params[0],context);
                                        String wwwshorturl = HttpUtils.getDocShortUrl("www",params[0],context);
                                        
                                        Map map = new HashMap();
                                        map.put("wap", shorturl);
                                        map.put("www", wwwshorturl);
                                        return map;
                                    }
                                    @Override
                                    protected void onPostExecute(Map result) {
                                        super.onPostExecute(result);
                                        String shorturl = (String)result.get("wap");
                                        String wwwshorturl   = (String)result.get("www");
                                        Intent intent = new Intent(Intent.ACTION_SEND);
                                        intent.setType("text/plain");
                                        intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
                                        intent.putExtra(Intent.EXTRA_TEXT, context.getResources()
                                                .getString(R.string.share_sms_tietext)
                                                + "《"
                                                + shareTitle
                                                + "》"
                                                + context.getResources().getString(R.string.share_with_u)
                                                + context.getResources().getString(R.string.share_url_wap)
                                                + shorturl
                                                + context.getResources().getString(R.string.share_url_www)
                                                + wwwshorturl);
                                        context.startActivity(Intent.createChooser(intent, title));
                                    }
                                }.execute(tieurl2);
                                
                              
                                
                                break;
                        }
                    }
                }).setNegativeButton("取消", null).show();
        
    }
    
    /**
     * 所有跟帖分享
     * @param context
     * @param title
     */
    public static void showShareDialog(final Context context, final String title, final String bi, final String docid, final String shareTitle) {
        new AlertDialog.Builder(context)
        .setTitle("分享")
        .setItems(new String[] {context.getResources().getString(R.string.share_to_weibo),
                context.getResources().getString(R.string.share_to_sina),
                context.getResources().getString(R.string.share_to_qq),
                context.getResources().getString(R.string.share_to_renren),
                context.getResources().getString(R.string.share_to_ydnote),
                context.getResources().getString(R.string.share_to_sms),
                context.getResources().getString(R.string.share_to_email),
                context.getResources().getString(R.string.share_to_other),
                },  
                new DialogInterface.OnClickListener(){

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        String shareurl = StringUtil.TIEURL + bi + "/" + docid + ".html";
                        
                        Intent shareintent = new Intent();
                        shareintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        shareintent.setClass(context, ShareToMicroBlog.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("sharetitle", shareTitle);
                        bundle.putString("shareurl", shareurl);
                        bundle.putBoolean("tie", true);
                        
                        switch(arg1) {
                        //网易微博
                        case Constant.SHARE_NETEASE:
                            bundle.putInt("sharetype", 0);
                            shareintent.putExtras(bundle);
                            context.startActivity(shareintent);
                                                            
                            break;
                        //新浪微博
                        case Constant.SHARE_SINA:
                            bundle.putInt("sharetype", 1);
                            shareintent.putExtras(bundle);
                            context.startActivity(shareintent);

                            break;
                        //腾讯微博
                        case Constant.SHARE_QQ:                                 
                            bundle.putInt("sharetype", 2);
                            shareintent.putExtras(bundle);
                            context.startActivity(shareintent);
                            break;
                        //人人网
                        case Constant.SHARE_RENREN:                                 
                            bundle.putInt("sharetype", 3);
                            shareintent.putExtras(bundle);
                            context.startActivity(shareintent);
                            break;
                        // 有道笔记
                        case Constant.SHARE_YDNOTE:
                            bundle.putInt("sharetype", 4);
                            
                            String tieurl = shareurl;
                            bundle.putString("sharetitle", getCommentHtmlString(shareTitle, tieurl, 4));
                            bundle.putString("sharetitleyd", shareTitle);
                            
                            shareintent.putExtras(bundle);
                            context.startActivity(shareintent);
                            break;
                        case Constant.SHARE_SMS:
                            tieurl = shareurl;
                            new AsyncTask<String, Integer, Map>(){

                                @Override
                                protected Map doInBackground(String... params) {
                                    // TODO Auto-generated method stub
                                    String shorturl = HttpUtils.getDocShortUrl("wap",params[0],context);
                                    String wwwshorturl = HttpUtils.getDocShortUrl("www",params[0],context);
                                    
                                    Map map = new HashMap();
                                    map.put("wap", shorturl);
                                    map.put("www", wwwshorturl);
                                    return map;
                                }
                                
                                @Override
                                protected void onPostExecute(Map result) {
                                    super.onPostExecute(result);
                                    
                                    String shorturl = (String)result.get("wap");
                                    String wwwshorturl   = (String)result.get("www");
                                    
                                    Intent sendIntent = new Intent(Intent.ACTION_VIEW);
                                    sendIntent.putExtra("sms_body", context.getResources().getString(R.string.share_sms_tietext)
                                            + "《"+shareTitle+"》"
                                            + context.getResources().getString(R.string.share_with_u)+":"
                                            + context.getResources().getString(R.string.share_url_wap)+" "+shorturl
                                            +" "+ context.getResources().getString(R.string.share_url_www)+" "+wwwshorturl);
                                    sendIntent.setType("vnd.android-dir/mms-sms");
                                    context.startActivity(sendIntent);
                                    
                                }
                                
                            }.execute(tieurl);
                            break;
                        case Constant.SHARE_EMAIL:
                            final List<ResolveInfo> sharelist = Tools.getShareTargets(context,"message/rfc822");
                            if(null!=sharelist && sharelist.size()>0){
                                try {       
                                    tieurl = shareurl;
                                    new AsyncTask<String, Integer, String>(){

                                        @Override
                                        protected String doInBackground(String... params) {
                                            // TODO Auto-generated method stub
                                            return HttpUtils.getDocShortUrl("www",params[0],context);
                                  
                                        }
                                        @Override
                                        protected void onPostExecute(String result) {
                                            super.onPostExecute(result);
                                            
                                            Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);                                
                                            emailIntent.setType("message/rfc822");
                                            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, 
                                                    context.getResources().getString(R.string.share_email_tietitle));
                                            
                                            String html = getCommentHtmlString(shareTitle, result, -1);
                                            
                                            emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(html));
                                            context.startActivity(Intent.createChooser(emailIntent, 
                                                    context.getResources().getString(R.string.select_email_client)));
                                        }
                                        
                                    }.execute(tieurl);                                       

                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Toast.makeText(context, 
                                            context.getResources().getString(R.string.share_email_failure), 
                                            Toast.LENGTH_SHORT).show();
                                }
                            }else{
                                Toast.makeText(context, 
                                        context.getResources().getString(R.string.share_email_noclient), 
                                        Toast.LENGTH_SHORT).show();
                            }
                            

                            break;
                        case Constant.SHARE_OTHER:
                            String tieurl2 = shareurl;
                            new AsyncTask<String, Integer, Map>(){

                                @Override
                                protected Map doInBackground(String... params) {
                                    // TODO Auto-generated method stub
                                    String shorturl = HttpUtils.getDocShortUrl("wap",params[0],context);
                                    String wwwshorturl = HttpUtils.getDocShortUrl("www",params[0],context);
                                    
                                    Map map = new HashMap();
                                    map.put("wap", shorturl);
                                    map.put("www", wwwshorturl);
                                    return map;
                                }
                                
                                @Override
                                protected void onPostExecute(Map result) {
                                    super.onPostExecute(result);
                                    
                                    String shorturl = (String)result.get("wap");
                                    String wwwshorturl   = (String)result.get("www");
                                    
                                    Intent intent = new Intent(Intent.ACTION_SEND);
                                    intent.setType("text/plain");
                                    intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
                                    intent.putExtra(Intent.EXTRA_TEXT,  context.getResources().getString(R.string.share_sms_tietext)
                                            + "《"+shareTitle+"》"
                                            + context.getResources().getString(R.string.share_with_u) 
                                            + context.getResources().getString(R.string.share_url_wap)+shorturl
                                            + context.getResources().getString(R.string.share_url_www)+wwwshorturl);
                                    context.startActivity(Intent.createChooser(intent, title));
                                    
                                }
                                
                            }.execute(tieurl2);
                            break;
                        }
                    }
                    
        })
        .setNegativeButton("取消", null)
        .show();
    }
    
    //获取跟贴信息
    private static String getCommentHtmlString(String docTitle, String shorturl, int type) {
		// TODO Auto-generated method stub
		StringBuilder html = new StringBuilder();
		html.append("我在网易新闻手机客户端，发现了跟贴：<html><head></head><body style=\"margin:0px; padding:0px;\">")
			.append("<center><div style=\"color:#464646;font-size:18px;font-weight:bold;\" >")
			.append(docTitle).append("</div>").append("<p>跟贴地址：<a href=\"")
			.append(shorturl).append("\">").append(shorturl).append("</a></p>").append("</div>");
		if(type == 4){
			html.append("<--insert-->");
		}
		html.append("</body></html>");
		return html.toString();
	}
}
